package data;

import java.math.BigInteger;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import com.google.common.collect.Lists;

public class VotingSet
{
    private List<VotingCard> _cards = Lists.newLinkedList();

    public VotingSet()
    {
    }

    public void addCard( VotingCard card )
    {
        _cards.add( card );
    }

    public int getVoteNumber( String candidateName )
    {
        for( int i = 0; i < _cards.size(); i++ )
        {
            VotingCard card = _cards.get( i );
            if( card.getVoted().get( 0 ).getName().startsWith( candidateName ) )
            {
                return i;
            }
        }
        throw new IllegalArgumentException( "CANDIDATE NOT FOUND" );
    }

    protected VotingSet( VotingCard sampleCard )
    {
        Random r = new Random();
        int size = sampleCard.getCandidates().size();
        boolean[] voted = new boolean[ size ];
        for( int i = size; i > 0; i-- )
        {
            int rand = r.nextInt( i );
            int j = 0;
            int moves = 0;
            while( j < rand )
            {
                if( !voted[ moves ] )
                {
                    j++;
                    moves++;
                }
                else
                {
                    while( voted[ moves ] )
                        moves++;
                }
            }
            while( voted[ moves ] )
                moves++;
            voted[ moves ] = true;
            VotingCard c = sampleCard.clone();
            c.setVoted( moves );
            _cards.add( c );
        }
    }

    public List<VotingCard> getCards()
    {
        return _cards;
    }

    public boolean isValid( Collection<String> candidates )
    {
        if( candidates.size() != _cards.size() )
            return false;
        BigInteger number = _cards.get( 0 ).getId();
        for( VotingCard c: _cards )
        {
            if( !number.equals( c.getId() ) )
                return false;
            List<Candidate> voted = c.getVoted();
            if( voted.size() != 1 )
                return false;
            Candidate voteFor = voted.get( 0 );
            String name = voteFor.getName();
            boolean found = true;
            for( String candidateName: candidates )
            {
                if( candidateName.equals( name ) )
                {
                    found = true;
                    break;
                }
            }
            candidates.remove( name );
            if( !found )
                return false;
        }
        return true;
    }
}
